# -*- coding:utf-8 -*-
import websocket
import hashlib
import base64
import hmac
import json
from urllib.parse import urlencode
import time
import ssl
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime
import _thread as thread

from gpt3_1 import Session
from timerReset import RepeatingTimer
import threading
import pyaudio

from voice import text2speak
import simpleaudio as sa

STATUS_FIRST_FRAME = 0  # 第一帧的标识
STATUS_CONTINUE_FRAME = 1  # 中间帧标识
STATUS_LAST_FRAME = 2  # 最后一帧的标识

welcome_sound = False

def func():
    global wakeFlag, myresult, count
    print("等待说话；" + str(count) + "秒")
    count += 1
    if count == 10:
        count = 0
        wakeFlag = False
        user_session.get_chat_response(myresult)
        # thread_it(False, user_session.get_chat_response, myresult)
        myresult = ""
        print("发送数据到GPT")


# class RepeatingTimer(Timer):
#     def run(self):
#         while not self.finished.is_set():
#             self.function(*self.args, **self.kwargs)
#             self.finished.wait(self.interval)

user_session = Session()
myresult = ""
count = 0
wait_speak = RepeatingTimer(1, func)
wakeFlag = False


class Ws_Param(object):
    # 初始化
    def __init__(self, APPID, APIKey, APISecret):
        self.APPID = APPID
        self.APIKey = APIKey
        self.APISecret = APISecret

        # 公共参数(common)
        self.CommonArgs = {"app_id": self.APPID}
        # 业务参数(business)，更多个性化参数可在官网查看
        self.BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin", "ptt": 0, "vinfo": 1,
                             "vad_eos": 10000}

    # 生成url
    def create_url(self):
        url = 'wss://ws-api.xfyun.cn/v2/iat'
        # 生成RFC1123格式的时间戳
        now = datetime.now()
        date = format_date_time(mktime(now.timetuple()))

        # 拼接字符串
        signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"
        signature_origin += "date: " + date + "\n"
        signature_origin += "GET " + "/v2/iat " + "HTTP/1.1"
        # 进行hmac-sha256进行加密
        signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
                                 digestmod=hashlib.sha256).digest()
        signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')

        authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
            self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
        # 将请求的鉴权参数组合为字典
        v = {
            "authorization": authorization,
            "date": date,
            "host": "ws-api.xfyun.cn"
        }
        # 拼接鉴权参数，生成url
        url = url + '?' + urlencode(v)
        # print("date: ",date)
        # print("v: ",v)
        # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释，比对相同参数时生成的url与自己代码生成的url是否一致
        # print('websocket url :', url)
        return url


# 收到websocket消息的处理
def on_message(ws, message):
    global myresult, count, wait_speak
    try:
        code = json.loads(message)["code"]
        sid = json.loads(message)["sid"]
        if code != 0:
            errMsg = json.loads(message)["message"]
            print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))

        else:
            global result
            data = json.loads(message)["data"]["result"]["ws"]
            result = ""
            for i in data:
                for w in i["cw"]:
                    result += w["w"]
            # print("sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False)))
            if result == '。' or result == '.。' or result == ' .。' or result == ' 。':
                pass
            else:

                if result.find("听得见吗") != -1:
                    sa.WaveObject.from_wave_file('listen.wav').play().wait_done()
                    print("我在，请吩咐")
                    myresult = ""
                    result = ""
                if result.find("清除对话") != -1:
                    sa.WaveObject.from_wave_file('clear_chat.wav').play().wait_done()
                    print("已清除")
                    myresult = ""
                    result = ""
                if result[-4:] == "结束对话":
                    sa.WaveObject.from_wave_file('wait.wav').play().wait_done()
                    result = result[:-2]
                    text = user_session.get_chat_response(myresult)
                    print("AI:")
                    print(text)
                    if not text=='False':
                        thread_it(True, text2speak(text))
                        myresult = ""
                        result = ""
                myresult += result
                print("翻译结果: %s。" % myresult)

    except Exception as e:
        print("receive msg,but parse exception:", e)


# 收到websocket错误的处理
def on_error(ws, error):
    global myresult
    myresult = ''
    print("### error:", error)


# 收到websocket关闭的处理
def on_close(ws):
    thread_it(False, start_Record, )
    global myresult
    myresult = ''
    print("### closed ###")
    # print("result:%(name)" % {"name": result})
    # print("result:{}".format(result))
    # print("result："+myresult)
    # pass


# 收到websocket连接建立的处理
def on_open(ws):
    def run(*args):
        global welcome_sound,myresult
        status = STATUS_FIRST_FRAME  # 音频的状态信息，标识音频是第一帧，还是中间帧、最后一帧
        CHUNK = 520  # 定义数据流块
        FORMAT = pyaudio.paInt16  # 16bit编码格式
        CHANNELS = 1  # 单声道
        RATE = 16000  # 16000采样频率
        p = pyaudio.PyAudio()
        # 创建音频流
        stream = p.open(format=FORMAT,  # 音频流wav格式
                        channels=CHANNELS,  # 单声道
                        rate=RATE,  # 采样率16000
                        input=True,
                        frames_per_buffer=CHUNK)
        if not welcome_sound:
            sa.WaveObject.from_wave_file('welcome.wav').play().wait_done()
            welcome_sound = True
        print("- - - - - - - Start Recording ...- - - - - - - ")
        try:
            for i in range(0, int(RATE / CHUNK * 60)):
                buf = stream.read(CHUNK)
                if not buf:  # 文件结束
                    status = STATUS_LAST_FRAME

                # 第一帧处理
                # 发送第一帧音频，带business 参数
                # appid 必须带上，只需第一帧发送
                if status == STATUS_FIRST_FRAME:

                    d = {"common": wsParam.CommonArgs,
                         "business": wsParam.BusinessArgs,
                         "data": {"status": 0, "format": "audio/L16;rate=16000",
                                  "audio": str(base64.b64encode(buf), 'utf-8'),
                                  "encoding": "raw"}}
                    d = json.dumps(d)
                    ws.send(d)
                    status = STATUS_CONTINUE_FRAME
                    # 中间帧处理
                elif status == STATUS_CONTINUE_FRAME:
                    d = {"data": {"status": 1, "format": "audio/L16;rate=16000",
                                  "audio": str(base64.b64encode(buf), 'utf-8'),
                                  "encoding": "raw"}}
                    ws.send(json.dumps(d))

                # 最后一帧处理
                elif status == STATUS_LAST_FRAME:
                    d = {"data": {"status": 2, "format": "audio/L16;rate=16000",
                                  "audio": str(base64.b64encode(buf), 'utf-8'),
                                  "encoding": "raw"}}
                    ws.send(json.dumps(d))
                    time.sleep(1)
                    break
        except Exception as e:
            # thread.start_new_thread(run, ())  # 开起新线程run
            myresult = ''
            print(f"发生错误: {e}")

            # thread.start_new_thread(run, ())  # 开起新线程run
        stream.stop_stream()
        stream.close()
        p.terminate()
        ws.close()

    thread.start_new_thread(run, ())  # 开起新线程run


def start_Record():
    global wsParam
    try:
        wsParam = Ws_Param(APPID='2440fe06', APISecret='NDk3NTdiZmIwYmNiYWM0MTVhZTUyNTA5',
                           APIKey='b9d24f11baae02ca67e4bb483a7c451c')
        websocket.enableTrace(False)
        wsUrl = wsParam.create_url()
        ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close)
        ws.on_open = on_open
        ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}, ping_timeout=10)
        # websocket说明 https://blog.csdn.net/tz_zs/article/details/119363470
    except Exception as e:
        print(e)

# TODO 记得修改 APPID、APIKey、APISecret

#
def thread_it(_bool, func, *args):
    t = threading.Thread(target=func, args=args)  # 调用func函数
    t.setDaemon(_bool)  # False设置为用户线程,True设置守护线程
    # 用户线程和守护线程的区别:
    # 主线程结束后用户线程还会继续运行，主线程结束后，如果没有用户线程，都是守护线程，那么结束（随之而来的是所有的一切烟消云散，包括所有的守护线程）。
    t.start()


#
#
# root = Tk()
# t = Text(root)
# t.pack()
# #
# tkinter.Button(root, text='go', command=lambda: thread_it(run, )).pack()
# root.mainloop()

if __name__ == "__main__":
    thread_it(False, start_Record, )
    # coro = myrun()
    # loop = asyncio.get_event_loop()
    # loop.run_until_complete(coro)
    # loop.close()
    # asyncio.run()
    # start_Record()
